package cn.tworice.system.service.feedback;

import cn.tworice.common.framework.mail.core.MailExecutor;
import cn.tworice.common.util.datatime.TimeUtils;
import cn.tworice.common.util.excel.InductsListenerService;
import cn.tworice.common.vo.RequestResult;
import cn.tworice.mybatis.query.MPJLambdaWrapperX;
import cn.tworice.mybatis.vo.PageParam;
import cn.tworice.system.controller.feedback.vo.FeedbackStatVO;
import cn.tworice.system.dao.feedback.SystemFeedbackDao;
import cn.tworice.system.dao.feedback.dto.FeedbackDTO;
import cn.tworice.system.dao.feedback.po.SystemFeedbackDO;
import cn.tworice.system.dao.feedback.po.SystemFeedbackTypeDO;
import org.springframework.stereotype.Service;

import java.util.*;
import javax.annotation.Resource;

@Service
public class SystemFeedbackService implements InductsListenerService<SystemFeedbackDO> {
    @Resource
    private SystemFeedbackDao dao;

    @Resource
    private MailExecutor mailExecutor;

    @Resource
    private SystemFeedbackTypeService typeService;

    public Map<String,Object> list(PageParam pageParam, SystemFeedbackDO entity) {
        if(entity.getTypeLevel()==null){
            return dao.selectJoinPage(pageParam, FeedbackDTO.class, new MPJLambdaWrapperX<SystemFeedbackDO>()
                    .eqIfPresent(SystemFeedbackDO::getId, entity.getId())
                    .eqIfPresent(SystemFeedbackDO::getCreator, entity.getCreator())
                    .eqIfPresent(SystemFeedbackDO::getFbType, entity.getFbType())
                    .eqIfPresent(SystemFeedbackDO::getFbContact, entity.getFbContact())
                    .selectAll(SystemFeedbackDO.class)
                    .select(SystemFeedbackTypeDO::getTypeName)
                    .leftJoin(SystemFeedbackTypeDO.class, SystemFeedbackTypeDO::getId, SystemFeedbackDO::getFbType)
                    .orderByDesc(SystemFeedbackDO::getCreateTime)
            );
        }else {
//        if(entity.getTypeLevel()==null || entity.getTypeLevel().isEmpty()) return new HashMap<>();

            return dao.selectJoinPage(pageParam, FeedbackDTO.class, new MPJLambdaWrapperX<SystemFeedbackDO>()
                    .eqIfPresent(SystemFeedbackDO::getId, entity.getId())
                    .eqIfPresent(SystemFeedbackDO::getCreator, entity.getCreator())
                    .eqIfPresent(SystemFeedbackDO::getFbType, entity.getFbType())
                    .eqIfPresent(SystemFeedbackDO::getFbContact, entity.getFbContact())
                    .in(SystemFeedbackTypeDO::getTypeLevel, entity.getTypeLevel())
                    .selectAll(SystemFeedbackDO.class)
                    .select(SystemFeedbackTypeDO::getTypeName)
                    .leftJoin(SystemFeedbackTypeDO.class, SystemFeedbackTypeDO::getId, SystemFeedbackDO::getFbType)
                    .orderByDesc(SystemFeedbackDO::getCreateTime)
            );
        }
    }

    public int set(SystemFeedbackDO entity) {
        if (entity.getId() == null) {
            return dao.insert(entity);
        } else {
//            entity.setUpdateTime(System.currentTimeMillis());
            this.sendMail(entity);
            return dao.updateById(entity);
        }
    }

    public int del(Integer[] ids) {
        return dao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public boolean saveBatch(List<SystemFeedbackDO> list) {
        return dao.insertBatch(list, list.size());
    }

    public SystemFeedbackDO info(int id) {
        return dao.selectById(id);
    }

    @Deprecated
    public List<Map<String,Object>> getTypeList() {
        List<Map<String,Object>> typeList = new ArrayList<>();
        Arrays.stream(FeedbackType.values()).forEach(item->{
            Map<String, Object> map = new HashMap<>();
            map.put("type", item.getType());
            map.put("msg", item.getMsg());
            typeList.add(map);
        });
        return typeList;
    }

    /**
     * 获取统计数据，时间单位（小时）
     * @return 返回客户端数据
     */
    public RequestResult getStat() {
        List<FeedbackStatVO> list = new ArrayList<>();
        List<SystemFeedbackTypeDO> typeListByState = typeService.getTypeListByState(SystemFeedbackConst.showStateCode);
        for (SystemFeedbackTypeDO typeDO : typeListByState) {
            FeedbackStatVO feedbackStatVO = new FeedbackStatVO();
            long total = this.getTotalByType(typeDO.getId());
            feedbackStatVO.setTotal(total);
            if (total > 0) {
                feedbackStatVO.setTimeStampCount(TimeUtils
                        .millisecondsToMinutes(
                                this.getTimeStampCountByType(typeDO.getId())
                        )
                );
                feedbackStatVO.setTimeStampAvg(TimeUtils
                        .millisecondsToMinutes(
                                this.getTimeStampAvgByType(typeDO.getId())
                        )
                );
            }else{
                feedbackStatVO.setTimeStampCount(0L);
                feedbackStatVO.setTimeStampAvg(0L);
            }
            feedbackStatVO.setTypeId(typeDO.getId());
            feedbackStatVO.setTypeLevel(typeDO.getTypeLevel());
            feedbackStatVO.setTypeName(typeDO.getTypeName());
            list.add(feedbackStatVO);
        }
        return RequestResult.success().appendData("list", list);
    }

    private long getTotalByType(int type) {
        return dao.selectCount(new MPJLambdaWrapperX<SystemFeedbackDO>().eq(SystemFeedbackDO::getFbType, type));
    }

    private long getTimeStampCountByType(int type) {
        return dao.selectTimeStampCountByType(type);
    }

    private long getTimeStampAvgByType(int type) {
        return dao.selectTimeStampAvgByType(type,SystemFeedbackConst.finishState);
    }

    private void sendMail(SystemFeedbackDO entity){
        if (SystemFeedbackConst.finishState.equals(entity.getFbState())) {
            mailExecutor.sendHtmlMail(entity.getFbContact(), "关于您反馈的内容，当前处理状态为："+entity.getFbState(), entity.getFbDeal());
        }
    }
}